package com.backend.springboot_project_demo.service;

import com.backend.springboot_project_demo.entity.LotteryConfig;
import com.backend.springboot_project_demo.entity.LotterySection;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CheckLotterySectionService {
    private final static int ZERO = 0;
    private final static int MIN_NUM = 1;
    private final static int MAX_NUM = 999;

    public boolean checkLotterySection(LotteryConfig config) {
        List<LotterySection> lotterySections = config.getLotterySections();
        List<LotterySection> sectionsForCheck = new ArrayList<>();
        for(LotterySection lotterySection: lotterySections) {
            if (isMixOtherRange(lotterySection, sectionsForCheck)) {
                return false;
            }
            if (!isLegalLotteryRange(lotterySection)) {
                return false;
            } else {
                sectionsForCheck.add(lotterySection);
            }
        }
        return true;
    }

    private boolean isMixOtherRange(LotterySection lotterySection, List<LotterySection> sectionsForCheck) {
        if (sectionsForCheck.size() <= ZERO) {
            return false;
        }
        for (LotterySection check: sectionsForCheck) {
            int checkMaxNum = check.getMaxNum();
            int checkMinMum = check.getMinNum();
            int maxNum = lotterySection.getMaxNum();
            int minNum = lotterySection.getMinNum();
            return !(checkMaxNum < minNum || checkMinMum > maxNum);
        }
        return true;
    }

    private boolean isLegalLotteryRange(LotterySection lotterySection) {
        int maxNum = lotterySection.getMaxNum();
        int minNum = lotterySection.getMinNum();
        return isTrueNum(minNum) && isTrueNum(maxNum) && (maxNum - minNum >= ZERO);
    }

    private boolean isTrueNum(int num) {
        return num >= MIN_NUM && num <= MAX_NUM;
    }

}
